<template>
  <div ref="scrollOuter" class="scroll_outer">
    <div ref="scrollInner">
      <slot name="scrollInner"/>
    </div>
    <NoMore v-if="data.page * offset >= data.count"/>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import NoMore from './NoMore'

export default {
  name: 'scroll',
  props: {
    data: {
      type: Object,
      default: () => {
        return {
          count: 0,
          list: [],
          page: 0
        }
      }
    },
    params: {
      type: Object,
      default: () => {
        return {
        }
      }
    },
    action: {
      type: String,
      default: ''
    },
    offset: {
      type: Number,
      default: 10
    }
  },
  components: {
    NoMore
  },
  computed: {
    ...mapGetters([
      'fetchStatus'
    ])
  },
  data () {
    return {
      fetching: false,
      winHeight: window.innerHeight
    }
  },
  watch: {
    fetchStatus () {
      if (this.fetchStatus) {
        this.fetching = false
      }
    }
  },
  methods: {
    scroll () {
      let inner = this.$refs.scrollInner
      let ih = inner.clientHeight
      let st = document.body.scrollTop || document.documentElement.scrollTop

      if (ih - this.winHeight - st < 10 && this.data.page * this.offset < this.data.count && !this.fetching) {
        this.fetching = true
        this.$store.commit('SET_SCROLL_FETCH_STATUS', { status: true })
        this.$store.dispatch(this.action, {
          page: this.data.page + 1,
          offset: this.offset,
          ...this.params
        })
      }
    }
  },
  mounted () {
    window.addEventListener('scroll', this.scroll, false)
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.scroll)
  }
}
</script>
